Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

348
Vistas
"Validation failed for object='user'. Error count: 1" instead of "email must not be null"

I have an api that validates and creates user. When I don't type email in request's body I receive

{
    "timestamp": "2020-11-26T13:55:40.116+00:00",
    "status": 400,
    "error": "Bad Request",
    "message": "Validation failed for object='user'. Error count: 1",
    "path": "/api/users"
}

I want to change message to more understable error like "email must be not null". That's how my model's property looks:

@NotNull
private String email;

And here is my controller's method:

@PostMapping("/users")
public ResponseEntity<User> addUser(@RequestBody @Valid User user) {
    User savedUser = manager.save(user);
    URI uri = ServletUriComponentsBuilder.fromCurrentRequest()
            .path("/{id}")
            .buildAndExpand(savedUser.getId())
            .toUri();
    return ResponseEntity.ok(savedUser);
}

I've tried to set custom message in @NotNull annotation, but the message doesn't change. Also when the error gets thrown console shows this message:

2020-11-26 15:09:11.460  WARN 7137 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public org.springframework.http.ResponseEntity<pl.vemu.socialApp.entities.User> pl.vemu.socialApp.controllers.UserController.addUser(pl.vemu.socialApp.entities.User) throws pl.vemu.socialApp.exceptions.user.UserWithEmailAlreadyExistException: [Field error in object 'user' on field 'email': rejected value [xsars.pl]; codes [Email.user.email,Email.email,Email.java.lang.String,Email]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.email,email]; arguments []; default message [email],[Ljavax.validation.constraints.Pattern$Flag;@2a50b33,.*]; default message [must be a well-formed email address]] ]

How to set the message in response json?
How to get rid of this message in console? Other errors don't show message in console.

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

The problem is that Spring by default doesn't send errors while binding. To enable it you have to add server.error.include-binding-errors=always in your application.properties.

over 4 years ago · Santiago Trujillo Denunciar

0

Instead of relying on "message" property, you can use "defaultMessage" property.

You can set a custom error message on @NotNull annotation.

@NotNull(message = "Name cannot be null")
private String name;

@NotNull(message = "email cannot be null")
@NotEmpty(message = "email cannot be empty")
private String email;

If validation fails for a field, spring will set these custom messages on "defaultMessage" property

As you said in the comments that you couldn't find defaultMessage, another approach (perhaps the dirty approach) would be to manually create the response body, you can refer the following sample code to build it:

@PostMapping("saveEmployee")
public ResponseEntity<?> eat(@RequestBody @Valid Employee employee, Errors errors) {
    if (errors.hasFieldErrors()) {
        FieldError fieldError = errors.getFieldError();
        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(fieldError.getDefaultMessage());
    }
    return ResponseEntity.ok(employee);
}

FieldError#getDefaultMessage() will expose the value of message attribute in @NotNull(message = "email can't be null")

over 4 years ago · Santiago Trujillo Denunciar

0

ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body("email must be not null");

and replace HttpStatus.UNPROCESSABLE_ENTITY with a suitable error code.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda